package com.oss.intercept.jwt;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.oss.utils.BaseContextHandler;
import com.oss.utils.constants.DataDictionary;
import com.oss.view.InvokeResult;

public class LoginInterceptor implements Interceptor {

    JWTUtil jwtUtil = new JWTUtil();


    @Override
    public void intercept(Invocation inv) {

        Controller controller = inv.getController();

        String token = controller.getCookie("access-token");
        if (token == null) {
            token = controller.getHeader("X-Requested-With");//找不到就去header中寻找
        }

        if (token != null) {
            IJWTInfo infoFromToken = jwtUtil.getInfoFromToken(token);
            if (infoFromToken != null) {
                String userId = infoFromToken.getId();
                if (userId != null) {
                    BaseContextHandler.setUserID(userId);
                    inv.invoke();
                }
            } else {
                controller.setCookie("access-token", null, 0);
                controller.renderJson(InvokeResult.failure(DataDictionary.UNLOGIN, "请重新登录"));
            }

        } else {
            controller.renderJson(InvokeResult.failure(DataDictionary.UNLOGIN, "请先登录"));
        }

    }
}
